﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using BLL;
using System.Text.RegularExpressions;
using System.Data;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

public partial class Spa_weixinreg : WeiPage
{
    PersonInfoBO pbo = new PersonInfoBO();
    IntegralChangeBO ibo = new IntegralChangeBO();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["code"] != null)
            {
                try
                {
                    string url = string.Format(@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + GetAppid() + "&secret=" + GetSecret() + "&code={0}&grant_type=authorization_code", Request.QueryString["code"].ToString());
                    string token = PostRequest(url);
                    if (token.Contains("7200"))
                    {
                        string[] b = token.Split('\"');
                        Session["FromUserName"] = b[13];
                        Session["ToUserName"] =GetAppid();
                    }
                }
                catch (Exception)
                {

                }
            }
            if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
            {
                string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
                string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
                Session["FromUserName"] = user;
                Session["ToUserName"] = user2;
                PersonInfo per = pbo.GetModel(user);
                if (per != null)
                {
                    Label1.Text = "你已注册";
                    Button1.Visible = false;
                    Button2.Visible = false;
                    Response.Redirect("Index.aspx");
                }
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string token = Token();
        Label1.Text = "";
        if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
        {

            if (txtPhone.Value.Trim().Length != 11)
            {
                Label1.Text = "手机号码为11位数字";
            }
            else if (Session["RanNum"] == null)
            {
                AlertMessage("请先获取验证码");
                return;
            }
            else if (txtNum.Value.Trim() == "")
            {
                Label1.Text = "请输入验证码";
            }
            else
            {
                si_DispMember_obService s1 = new si_DispMember_obService();
                dt_DispMember_req w1 = new dt_DispMember_req();
                w1.ZTYPE = "0101";
                w1.MOB_NUMBER = txtPhone.Value.Trim();
                dt_DispMember_res dt1 = s1.si_DispMember_ob(w1);
                if (dt1.ZCRMT316 == null)
                {
                    Label1.Text = "客户不存在，请进行注册";
                }
                else
                {
                    string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
                    string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
                    PersonInfo per = pbo.GetModel(user);
                    if (per != null)
                    {
                        Label1.Text = "你已经验证成功";
                        Button2.Visible = false;
                        Button1.Visible = false;

                    }
                    else
                    {
                        per = pbo.GetModel("", txtPhone.Value);
                        if (txtNum.Value == "")
                        {
                            Label1.Text = "请获取验证码";
                        }
                        else if (Session["RanNum"] != null && Session["RanNum"].ToString() != txtNum.Value.Trim())
                        {
                            Label1.Text = "验证码不正确。";
                        }
                        else
                        {
                            if (per != null)
                            {
                                per.FromUserName = user;
                                per.WX_DATE = DateTime.Now;
                                int num = pbo.Update(per);
                                if (num > 0)
                                {
                                    Label1.Text = "验证成功";
                                    try
                                    {
                                        si_UploadMemberShip_obService s = new si_UploadMemberShip_obService();
                                        dt_UploadMemberShip_req w = new dt_UploadMemberShip_req();
                                        ZCRMT316 z = new ZCRMT316();
                                        z.TYPE = "0101";
                                        z.BPEXT = per.PersonNo;
                                        z.MOB_NUMBER = per.Phone;
                                        z.ZC023 = user;
                                        w.ZCRMT316 = new ZCRMT316[] { z };
                                        dt_UploadMemberShip_res dt = s.si_UploadMemberShip_ob(w);


                                        //查找数据库判断是否添加过数据
                                        Z_GET_ACTIVITY_DETAIL_TELBO zga = new Z_GET_ACTIVITY_DETAIL_TELBO();
                                        string strWhere = string.Format(" PROCESS_TYPE = 'ZXY' and CHECK_FLAG='Y' and Phone = '{0}'", per.Phone);
                                        DataSet ds = zga.GetList(strWhere);
                                        if (ds == null || ds.Tables[0].Rows.Count == 0)
                                        {
                                            //送积分
                                            ActCreateTel(per.Phone);
                                        }
                                       
                                    }
                                    catch (Exception)
                                    {

                                    }
                                    AlertMessage("绑定成功");

                                    string Access_token = Token();
                                    var postUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_token;
                                    string d = @"{
    ""touser"":""{0}"",
    ""msgtype"":""text"",
    ""text"":
    {
         ""content"":""恭喜你绑定成功,获得佰草集汉方SPA 50 积分,另加一张携程电子抵用券（100元）,使用密码为：dfcf100""
    }
}";
                                    d = d.Replace("{0}", Session["FromUserName"].ToString());
                                    var resMessage = HttpXmlPostRequest(postUrl, d, Encoding.UTF8);

                                    Button2.Visible = false;
                                    Button1.Visible = false;                                   
                                    Response.Redirect("Index.aspx");
                                }
                            }
                            else
                            {
                                try
                                {


                                    per = new PersonInfo();
                                    per.addr = dt1.ZCRMT316[0].PSTREET == null ? "" : dt1.ZCRMT316[0].PSTREET;
                                    per.area = dt1.ZCRMT316[0].REGION == null ? "" : dt1.ZCRMT316[0].REGION;
                                    per.BIRTHDAY = dt1.ZCRMT316[0].BIRTHDT == null ? DateTime.Parse("1900-01-01") : dt1.ZCRMT316[0].BIRTHDT;
                                    //per.CreateDate = dt1.ZCRMT316[0].REG_DATE == null ? DateTime.Parse("0001-01-01") : dt1.ZCRMT316[0].REG_DATE;
                                    per.CreateDate = DateTime.Now;
                                    per.EMAIL = dt1.ZCRMT316[0].CSMTP_ADDR == null ? "" : dt1.ZCRMT316[0].CSMTP_ADDR;
                                    per.FromUserName = user;
                                    per.LAST_DATE = DateTime.Now;
                                    per.MEM_DATE = DateTime.Now;
                                    per.MEM_LEVEL = dt1.ZCRMT316[0].ZTIER == null ? "" : getlv(dt1.ZCRMT316[0].ZTIER);
                                    per.Name = dt1.ZCRMT316[0].NAME1_TEXT == null ? "" : dt1.ZCRMT316[0].NAME1_TEXT;
                                    per.PersonNo = dt1.ZCRMT316[0].BPEXT == null ? "" : dt1.ZCRMT316[0].BPEXT;
                                    per.Phone = txtPhone.Value;
                                    per.REMARK = "";
                                    per.Sex = dt1.ZCRMT316[0].XSEX == "2" ? true : false;
                                    per.Store = dt1.ZCRMT316[0].DEPTID == null ? "" : dt1.ZCRMT316[0].DEPTID;
                                    //string s=dt1.ZCRMT316[0].ZCCUR_POINT.ToString() 
                                    per.SumIntegral = Convert.ToInt32(dt1.ZCRMT316[0].ZCCUR_POINT);
                                    per.SurplusIntegral = Convert.ToInt32(dt1.ZCRMT316[0].ZCCUR_POINT);
                                    per.WX_DATE = DateTime.Now;
                                    per.YZM = txtNum.Value;
                                    ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
                                    string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + user;
                                    string b = PostRequest(url);
                                    string[] a = b.Split('\"');
                                    if (a.Length == 35)
                                    {
                                        if (a[9].ToString() != "")
                                        {
                                            per.WXName = a[9].ToString();
                                            //wjbo.Update(wjclass);
                                        }
                                    }
                                    //per.YZM ="123456";
                                    int num = pbo.Add(per);
                                    if (num > 0)
                                    {
                                        //Label1.Text = "验证成功";
                                        try
                                        {
                                            si_UploadMemberShip_obService s = new si_UploadMemberShip_obService();
                                            dt_UploadMemberShip_req w = new dt_UploadMemberShip_req();
                                            ZCRMT316 z = new ZCRMT316();
                                            z.TYPE = "0101";
                                            z.BPEXT = per.PersonNo;
                                            z.MOB_NUMBER = per.Phone;
                                            z.ZC023 = user;
                                            w.ZCRMT316 = new ZCRMT316[] { z };
                                            dt_UploadMemberShip_res dt = s.si_UploadMemberShip_ob(w);

                                            //查找数据库判断是否添加过数据
                                            Z_GET_ACTIVITY_DETAIL_TELBO zga = new Z_GET_ACTIVITY_DETAIL_TELBO();
                                            string strWhere = string.Format(" PROCESS_TYPE = 'ZXY' and CHECK_FLAG='Y' and Phone = '{0}'", per.Phone);
                                            DataSet ds = zga.GetList(strWhere);
                                            if (ds == null || ds.Tables[0].Rows.Count == 0)
                                            {
                                                //送积分
                                                ActCreateTel(per.Phone);
                                            }
                                            
                                        }
                                        catch (Exception)
                                        {

                                        }
                                        AlertMessage("绑定成功");

                                        string Access_token = Token();
                                        var postUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_token;
                                        string d = @"{
    ""touser"":""{0}"",
    ""msgtype"":""text"",
    ""text"":
    {
         ""content"":""恭喜你绑定成功,获得佰草集汉方SPA 50 积分,另加一张携程电子抵用券（100元）,使用密码为：dfcf100""
    }
}";
                                        d = d.Replace("{0}", Session["FromUserName"].ToString());
                                        var resMessage = HttpXmlPostRequest(postUrl, d, Encoding.UTF8);

                                        Button2.Visible = false;
                                        Button1.Visible = false;
                                        //Response.Redirect("Index.aspx");

                                    }
                                }
                                catch (Exception ee)
                                {
                                   Response.Write( ee.Message);

                                }
                            }
                        }
                    }
                }
                //}
            }
        }
    }

    private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

    public string getlv(string lv)
    {
        if (lv == "ZSMCJ0102")
            return "珍珠卡会员";
        if (lv == "ZSMCJ0103")
            return "翡翠卡会员";
        if (lv == "ZSMCJ0104")
            return "钻石卡会员";
        else
            return "绑定会员";
    }




    /// <summary>
    /// 在客户端弹出对话框
    /// </summary>
    public void AlertMessage(string message)
    {
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");window.location.href='Index.aspx';</script>");
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        // numT.Value = "60";
        try
        {
            Label1.Text = "";
            if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
            {
                string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
                string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
                si_DispMember_obService s1 = new si_DispMember_obService();
                dt_DispMember_req w1 = new dt_DispMember_req();
                w1.ZTYPE = "0101";
                w1.MOB_NUMBER = txtPhone.Value.Trim();
                dt_DispMember_res dt1 = s1.si_DispMember_ob(w1);
                if (dt1.ZCRMT316 == null)
                {
                    Label1.Text = "客户不存在，请进行注册";
                }
                else
                {
                    PersonInfo per = pbo.GetModel("", txtPhone.Value);

                    if (txtPhone.Value.Length == 11)
                    {
                        Random r = new Random();
                        int num = r.Next(100000, 999999);
                        //string message = string.Format("本次微信平台获取的验证码是：" + num);
                        string message = string.Format("本次微信平台获取的验证码是：[[" + num + "]]。如非本人操作，请致电400-820-3988");
                        string msg = new SendDX().Send(message, txtPhone.Value, 0);
                        if (msg == "发送成功")
                        {
                            Label1.Text = "发送成功,请耐心等待";
                            Session["RanNum"] = num.ToString();
                            //Button2.Visible = false;
                            numT.Value = "60";
                            //AlertMessage("因相关管控，经特殊处理，电信、联通客户将由136-1175-7392发送注册或绑定验证码，该号码仅提供验证码发送服务，请勿直接回复任何信息。");
                            //AlertMessage("请注意查收短信");
                        }
                        else
                        {
                            Session["RanNum"] = num.ToString();
                            Label1.Text = "发送失败";
                        }
                        if (per != null)
                        {
                            per.YZM = num.ToString();
                            pbo.Update(per);
                        }
                        //else
                        //{


                        //}
                    }
                    else
                    {
                        Label1.Text = "请输入正确的手机号";
                    }

                }
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message.ToString();
        }
    }

    public string OrderId()
    {
        string orderId = DateTime.Now.ToString("MMddHHmmss");
        return orderId;
    }
    public void ActCreateTel(string phone)
    {
        si_ActCreateTel_obService si = new si_ActCreateTel_obService();
        dt_ActCreateTel_req req = new dt_ActCreateTel_req();
        // 数据源类型 
        req.TYPE = "0101";
        // 会员手机号    
        req.MOB_NUMBER = phone;
        //处理标识 
        req.OBJECT_ID = OrderId();
        //活动单据类型	
        req.PROCESS_TYPE = "ZXY";
        //外部会员卡号	"会员卡号(如已传输手机号，可不用填写会员卡号)"
        req.BPEXT = "";
        //积分抽奖日期	日期
        req.POSTING_DATE = DateTime.Today;
        req.POSTING_DATESpecified = true;
        //产品 ID	
        req.PRODUCT_ID = "V0004";
        //产品数量	默认为1
        req.QUANTITY = "1";
        req.QUANTITYSpecified = true;
        //出售产品的计量单位  没有为空
        req.QTY_UNIT = "";
        //积分类型	
        req.POINT_TYPE = "ZSMJF01";
        //积分数
        req.POINTS = "50";
        req.POINTSSpecified = true;
        //单据全局活动ID
        req.CAMPAIGN_HE_ID = "C-00001706";

        dt_ActCreateTel_res res = si.si_ActCreateTel_ob(req);

        foreach (var item in res.I_ZCRMT047)
        {
            Z_GET_ACTIVITY_DETAIL_TELBO z = new Z_GET_ACTIVITY_DETAIL_TELBO();
            z.Add(new Z_GET_ACTIVITY_DETAIL_TEL
            {
                TYPE = item.TYPE,
                OBJECT_ID = item.OBJECT_ID,
                PROCESS_TYPE = item.PROCESS_TYPE,
                CHECK_FLAG = item.CHECK_FLAG,
                MESSAGE = item.MESSAGE,
                Phone = phone
            }
            );

        }

    }




}